<template>
  <el-card>
    <div class="card-header">
      <span>入库发票</span>
    </div>
  </el-card>
  <el-card>
    <el-form :inline="true">
      <el-form-item :model="listForm" label="选择供货商" >
        <el-select
          v-model="listForm.supplier_id"
          filterable
          autocomplete="off"
          placeholder="请选择客户"
          style="width: 100%"
          clearable>
        <el-pagination
            v-model:page-size="supplierForm.size"
            v-model:current-page="supplierForm.page"
            :total="supplierTotal"
            style="width: 100%"
            layout="prev, pager, next"
            @current-change="suppliers"
        />
        <el-option v-for="(supplier,idx) in supplierList" :label="`${supplierForm.size * (supplierForm.page-1) + idx+1}. ${supplier.name}`" :value="supplier.id" :key="idx"/>
      </el-select>
      </el-form-item>
      <el-form-item label="">
        <perms-button
            perms="inbound_invoice:receipt:list"
            :type="Types.success"
            :plain="true"
            @action="refresh"/>
      </el-form-item>
      <el-form-item label="">
        <perms-button
            perms="inbound_invoice:receipt:add"
            :type="Types.primary"
            :plain="true"
            @action="showDialog('add')"/>
      </el-form-item>
    </el-form>
    <el-table :data="invoices" :border="true">
      <template #empty>
        <el-empty/>
      </template>
      <el-table-column type="index" width="50"/>
      <el-table-column prop="supplier_name" label="供货商" min-width="100"/>
      <el-table-column prop="total" label="发票金额" min-width="100"/>
      <el-table-column prop="tax" label="税率(%)" min-width="100">
        <template #default="scope">
          {{scope.row.tax}}%
        </template>
      </el-table-column>
      <el-table-column label="税额" min-width="100">
        <template #default="scope">
          {{(scope.row.total * scope.row.tax /100).toFixed(2)}}
        </template>
      </el-table-column>
      <el-table-column prop="date" label="开票日期" min-width="100">
        <template #default="scope">
          {{dateFormat(scope.row.date)}}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260">
        <template #default="scope">
          <perms-button
              perms="inbound_invoice:receipt:update"
              :type="Types.primary"
              :plain="true"
              @action="showDialog('update', scope.row)"/>
          <el-popconfirm
              :icon="InfoFilled"
              icon-color="#F56C6C"
              :title='`确认删除当前发票？`'
              cancel-button-text="取消"
              confirm-button-text="确认删除"
              cancel-button-type="info"
              confirm-button-type="danger"
              @confirm="remove(scope.row.id)"
              width="300"
          >
            <template #reference>
              <perms-button
                  perms="inbound_invoice:receipt:delete"
                  :type="Types.danger"
                  :plain="true"
                  @action="refresh"/>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        class="page"
        v-model:current-page="listForm.page"
        v-model:page-size="listForm.size"
        :page-sizes="[30, 40, 50, 100]"
        :disabled="loading"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="list"
        @current-change="list"
    />
  </el-card>
  <el-dialog :close-on-click-modal="false" v-model="visible" title="添加供货商发票" :draggable="true" width="1200px">
    <el-form :model="invoiceForm" label-width="120px">
      <el-form-item label="开票日期">
        <el-date-picker
            v-model="invoiceForm.date"
            type="date"
            value-format="X"
            placeholder="选择开票日期"
        />
      </el-form-item>
      <el-form-item label="供货商">
        <el-select
            v-model="listForm.supplier_id"
            filterable
            autocomplete="off"
            placeholder="请选择客户"
            style="width: auto"
            clearable>
          <el-pagination
              v-model:page-size="supplierForm.size"
              v-model:current-page="supplierForm.page"
              :total="supplierTotal"
              style="width: 100%"
              layout="prev, pager, next"
              @current-change="suppliers"
          />
          <el-option v-for="(supplier,idx) in supplierList" :label="`${supplierForm.size * (supplierForm.page-1) + idx+1}. ${supplier.name}`" :value="supplier.id" :key="idx"/>
        </el-select>
      </el-form-item>
      <el-form-item label="发票金额">
        <el-input-number v-model.number="invoiceForm.total" :min="0" :precision="1" :step="1" autocomplete="off" :controls="false" style="width: 220px"/> 元
      </el-form-item>
      <el-form-item label="税率(%)">
        <el-input-number v-model.number="invoiceForm.tax" :min="0" :max="100" :precision="1" :step="1" autocomplete="off" :controls="false" style="width: 220px"/> %
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
//1.统计发票汇总数据
import {InboundInvoiceAddR, InboundInvoiceListR, InboundInvoiceSummaryR, InboundInvoiceRemoveR, InboundInvoiceUpdateR} from "@/api/inbound_invoice";
import {ElMessage} from "element-plus";
import {
  InboundInvoiceItem,
  InboundInvoiceListRequest,
  InboundInvoiceRequest,
  InboundInvoiceSummary
} from "@/interface/inbound_invoice";
import {onMounted, reactive, ref} from "vue";
import * as dayjs from "dayjs";
import {InfoFilled} from "@element-plus/icons-vue";
import {SupplierListR} from "@/api/suppliers";
import PermsButton from '@/components/PermsButton.vue'
import {Types} from "@/interface/enum";
import {ListRequest} from "@/interface/stockout";

//分页参数
const listForm = ref<InboundInvoiceListRequest>({page:1, size:10})
const loading = ref<boolean>(false)
const supplierForm = reactive<InboundInvoiceListRequest>({page: 1, size: 5})

const visible = ref<boolean>(false)

//入库发票列表
const invoices = ref<InboundInvoiceItem[]>()
const total = ref<number>(0)

const list = () => {
  loading.value = true
  InboundInvoiceListR(listForm.value).then(res => {
    loading.value = false
    return res.data
  }).then(res => {
    switch (res.code) {
      case 200:
        invoices.value = res.data.list
        total.value = res.data.total
        break
      case 204:
        invoices.value = []
        break
      default:
        //ElMessage.error(res.msg)
    }
  }).catch(err => {
    loading.value = false
    console.log('err:', err.toString())
    ElMessage.error('请求供货商发票列表失败')
  })
}

const initListForm = () => {
  return <InboundInvoiceListRequest>{
    page: 1,
    size: 10,
    supplier_name: '',
  }
}
const initInvoice = () => {
  return <InboundInvoiceItem>{
    id: 0,//id
    supplier_id: 0,//供货商id
    supplier_name: '',//供货商名称
    total: 0,//发票金额(元)
    tax: 0,//税率(%)
    date: 0,//开票日期
    created_at: 0,//已开票金额
    updated_at: 0,//已开票税额
  }
}

type Supplier = {
  id: number,//供货商id
  name: string//供货商名称
  supplier_id: number,//供货商
  has_tax: boolean,//是否含税
  tax: number,//税率(%)
}
//供货商列表
const supplierList = ref<Supplier[]>()
const supplierTotal = ref<number>(0)
const suppliers = () => {
  loading.value = true
  SupplierListR(supplierForm).then(res => {
    loading.value = false
    return res.data
  }).then(res => {
    if (res.code === 200) {
      supplierList.value = res.data.list as Supplier[]
      supplierTotal.value = res.data.total
    } else {
      //ElMessage.error(res.msg)
    }
  }).catch(err => {
    loading.value = false
    console.log('err:', err)
  })
}


//添加、修改发票
const invoiceForm = ref<InboundInvoiceItem>(initInvoice())
const initInvoiceForm = () => {
  return {
    id: 0,
    supplier_id: 0,
    supplier_name: '',
    total: 0,
    tax: 0,
    date: 0,
    created_at: 0,
    updated_at: 0,
  }
}

//动作标识
const action = ref<string>('')
//showDialog
const showDialog = (act: string, row?: InboundInvoiceItem) => {
  action.value = act
  switch (act) {
    case 'add':
      invoiceForm.value = initInvoiceForm()
      visible.value = true
      break
    case 'update':
      console.log('发票更新表单：', row)
      invoiceForm.value = row as InboundInvoiceItem
      visible.value = true
      break
    default:
      ElMessage.warning('未知操作')
  }
}

//提交
const handleSubmit = () => {
  switch (action.value) {
    case 'add':
      add()
      break
    case 'update':
      update()
      break
    default:
      ElMessage.warning('未知操作')
  }
}

//添加发票
const add = () => {
  loading.value = true
  InboundInvoiceAddR(invoiceForm.value).then(res => {
    loading.value = false
    return res.data
  }).then(res => {
    if (res.code === 200) {
      visible.value = false
      list()
      ElMessage.success('发票添加成功')
    } else {
      //ElMessage.error(res.msg)
    }
  }).catch(err => {
    loading.value = false
    console.log('err:', err)
  })
}

//删除发票
const remove = (id: number) => {
  loading.value = true
  let req = <InboundInvoiceRequest>{id:id}
  InboundInvoiceRemoveR(req).then(res => {
    loading.value = false
    return res.data
  }).then(res => {
    if (res.code === 200) {
      list()
      ElMessage.success('发票删除成功')
    } else {
      //ElMessage.error(res.msg)
    }
  }).catch(err => {
    loading.value = false
    console.log('err:', err)
  })
}


//修改发票信息
const update = () => {
  console.log('发票信息:', invoiceForm.value)
  loading.value = true
  InboundInvoiceUpdateR(invoiceForm.value).then(res => {
    loading.value = false
    return res.data
  }).then(res => {
    if (res.code === 200) {
      visible.value = false
      list()
      ElMessage.success('发票修改成功')
    } else {
      //ElMessage.error(res.msg)
    }
  }).catch(err => {
    loading.value = false
    console.log('err:', err)
  })
}


//时间格式
const dateFormat = (timestamp:number) => {
  return dayjs.unix(timestamp).format('YYYY-MM-DD')
}

//刷新所有接口
const refresh = () => {
  suppliers()
  list()
}

onMounted(() => {
  refresh()
  invoiceForm.value = initInvoiceForm()
})

</script>

<style lang="less" scoped>
.el-card {
  margin-bottom: 20px;
}
.el-row {
  margin-bottom: 20px;
}

.page {
  margin-top: 10px;
}
.card {
  min-height: 200px;
  color: white;
}

.card-invoice {
  background-color: #8683bd;
}

.card-supplier {
  background-color: #79bbff;
}

.content-between{
  display: flex;
  justify-content: space-between;
}
.content-column {
  display: flex;
  flex-direction: column;
  //justify-content: space-between;


  &-title {
    //font-size: 16px;
    display: inline-flex;
    flex: 0 0 auto;
    justify-content: flex-end;
    width: 100px;
    padding-right: 10px;
  }
  &-data {
    font-size: 28px;
    //margin-left: 80px;
  }

}
</style>
